package com.ahdms.es.util;

import com.ahdms.es.gm.constant.IKIObjectIdentifiers;
import com.ahdms.es.gm.v4.SES_Signature;
import org.bouncycastle.asn1.ASN1BitString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.security.PublicKey;
import java.util.Properties;

/**
 * @author qinxiang
 * @date 2021-04-07 14:02
 */
public class TestSesSignUtils {

    public static void main(String[] args) throws Exception {
        byte[] certDER = FileUtils.fileToByte("E:/ofd.cer");
        Certificate cert = Certificate.getInstance(certDER);

//        java.security.cert.Certificate signCert = new CertificateFactory()
//                .engineGenerateCertificate(new ByteArrayInputStream(certDER));
//        PublicKey publicKey = signCert.getPublicKey();
//        byte[] signData = FileUtils.fileToByte("E:/SignedValue2.dat");
////        byte[] signData = FileUtils.fileToByte("E:/TestReport.dat");
//
//        ASN1Sequence instance = ASN1Sequence.getInstance(signData);
//        int size = instance.size();
//        System.out.println("size: "+size);
////        Enumeration<?> e = instance.getObjects();
//        //1. 检测数据结构
//        SES_Signature ses_signature = SES_Signature.getInstance(signData);
//        //2. 检测签名值
//        System.out.println(verifySignData(ses_signature));
    }

    public static boolean verifySignData(SES_Signature ses_signature) throws Exception{
        ASN1BitString signature = ses_signature.getSignature();
        byte[] certDER = ses_signature.getCert().getOctets();
        Certificate cert = Certificate.getInstance(certDER);
        java.security.cert.Certificate signCert = new CertificateFactory()
                .engineGenerateCertificate(new ByteArrayInputStream(certDER));
        String algorithm = ses_signature.getSignatureAlgID().getId();

        boolean der = SM2Utils.verifySign(cert.getTBSCertificate().getSubjectPublicKeyInfo().getPublicKeyData().getOctets(), ses_signature.getToSign().getEncoded("DER"), signature.getOctets());
        System.out.println("der:"+der);
        return der;
//        //验证签名值
//        Signature sg = Signature.getInstance(algorithm, new BouncyCastleProvider());
//        // 用公钥初始化签名工具
//        PublicKey publicKey = signCert.getPublicKey();
//        sg.initVerify(signCert.getPublicKey());
//        // 添加要校验的数据
//        sg.update(ses_signature.getToSign().getEncoded("DER"));
//        return sg.verify(signature.getOctets());
    }

    public static boolean sm2VerifySign(byte[] certDER,byte[] data,byte[] signData){
        byte[] pubkey = CertTools.getSignPublicKey(Certificate.getInstance(certDER));
        boolean verifyResult = SM2Utils.verifySign(pubkey, data, signData);
        return verifyResult;
    }

}
